<template>
  <view class="user-detail container">
    <!-- <image
      v-if="projectInfo.log"
      class="user-detail-log"
      :src="$photo(projectInfo.log)"
    >
    </image>
    <view class="user-detail-content">
      <view class="content-message">
        <view class="flex flex-item-center justify-between">
          <view class="user-name">{{ projectInfo.nickname }}</view>
        </view>

        <view class="flex flex-item-center justify-between">
          <view class="flex flex-item-center">
            <u-icon name="star-fill" color="#F7CF51" size="20"></u-icon>
            <span class="star-number" style="margin-left: 8rpx">
              {{ getAverageScore(detailData._id) }}
            </span>
          </view>

          <view class="flex flex-item-center">
            <u-icon name="map-fill" size="20" color="#C5C5C5"></u-icon>
            <span
              style="margin-left: 8rpx; color: '#333'"
              v-if="detailData.server_address"
            >
              {{
                distance(
                  detailData.server_address.split(",")[1],
                  detailData.server_address.split(",")[0]
                )
              }}km
            </span>
            <span style="margin-left: 8rpx; color: '#333'" v-else>未知</span>
          </view>
        </view>

        <view class="order-number">
          订单
          <text v-if="filterOrderData[detailData._id]">
            {{
              filterOrderData[detailData._id].length
                ? Number(filterOrderData[detailData._id].length) > 100
                  ? "100+"
                  : filterOrderData[detailData._id].length
                : 0
            }}
          </text>
          <text v-else>0 </text>
          | 评价
          <text v-if="filterEvaluateData[detailData._id]">
            {{
              filterEvaluateData[detailData._id].length
                ? Number(filterEvaluateData[detailData._id].length) > 500
                  ? "500+"
                  : filterEvaluateData[detailData._id].length
                : 0
            }}
          </text>
          <text v-else>0 </text>
        </view>
      </view>
      <view class="content-project">
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">服务</view>
          <view class="project-item">{{ projectInfo.status }}</view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">项目</view>
          <view v-if="projectInfo.point" class="project-item text-ellipsis"
            >{{ projectInfo.point.join(" ") }}
          </view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">资质</view>
          <view class="project-item">{{ projectInfo.qualification }}</view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">保障</view>
          <view class="project-item">未服务全额退·爽约包赔·极速退款</view>
        </view>
      </view>
      <view class="content-introduction">
        <view class="title">技师简介</view>
        <view class="introduction-album">
          <u-album
            v-if="projectInfo.album"
            :urls="projectInfo.album"
            maxCount="4"
            rowCount="4"
          ></u-album>
        </view>
        <view class="introduction-text">
          {{ projectInfo.text }}
        </view>
      </view>
    </view> -->

    <image
      v-if="detailData.work_img"
      class="user-detail-log"
      :src="$photo(detailData.work_img)"
    >
    </image>
    <view class="user-detail-content">
      <view class="content-message">
        <view class="flex flex-item-center justify-between">
          <view class="user-name">{{ detailData.nickname }}</view>
        </view>

        <view class="flex flex-item-center justify-between">
          <view
            class="flex flex-item-center"
            v-if="getAverageScore(detailData._id)"
          >
            <u-icon name="star-fill" color="#F7CF51" size="20"></u-icon>
            <span class="star-number" style="margin-left: 8rpx">
              {{ getAverageScore(detailData._id) }}
            </span>
          </view>
          <view style="color: #666" v-else>暂未参与评分</view>

          <view class="flex flex-item-center">
            <u-icon name="map-fill" size="20" color="#C5C5C5"></u-icon>
            <span
              style="margin-left: 8rpx; color: '#333'"
              v-if="detailData.technician_address"
            >
              {{
                distance(
                  detailData.technician_address.split(",")[0],
                  detailData.technician_address.split(",")[1]
                )
              }}km
            </span>
            <span style="margin-left: 8rpx; color: '#333'" v-else>未知</span>
          </view>
        </view>

        <view class="order-number">
          订单
          <text v-if="filterOrderData[detailData._id]">
            {{
              filterOrderData[detailData._id].length
                ? Number(filterOrderData[detailData._id].length) > 100
                  ? "100+"
                  : filterOrderData[detailData._id].length
                : 0
            }}
          </text>
          <text v-else>0 </text>
          | 评价
          <text v-if="filterEvaluateData[detailData._id]">
            {{
              filterEvaluateData[detailData._id].length
                ? Number(filterEvaluateData[detailData._id].length) > 500
                  ? "500+"
                  : filterEvaluateData[detailData._id].length
                : 0
            }}
          </text>
          <text v-else>0 </text>
        </view>
      </view>
      <view class="content-project">
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">服务</view>
          <view class="project-item">{{
            detailData.status === 0
              ? detailData.status === 1
                ? "可服务"
                : "服务中"
              : "不可服务"
          }}</view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">项目</view>
          <view class="project-item text-ellipsis">
            <!-- {{ serverInfo.includes_project_names }} -->
            <text v-for="(item, index) of inCludesProjectList" :key="index">
              {{ item.name }}、
            </text>
          </view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">资质</view>
          <view class="project-item">{{
            serverInfo.server_certification
          }}</view>
        </view>
        <view class="flex flex-item-center">
          <view class="project-label" style="margin-right: 30rpx">保障</view>
          <view class="project-item">{{ serverInfo.server_assure }}</view>
        </view>
      </view>
      <view class="content-introduction">
        <view class="title">技师简介</view>
        <view class="introduction-album" v-if="detailData.certificate_img">
          <u-album
            :urls="handleImg(detailData.certificate_img)"
            maxCount="4"
            rowCount="4"
          ></u-album>
        </view>
        <view class="introduction-text">
          {{ detailData.introduction }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getModelList, getModelInfo } from "@/api";
import { getSearchFilter } from "@/common/function";
import { mapState } from "vuex";
export default {
  data() {
    return {
      // 详情信息
      detailData: {},
      // 全部订单数据
      allOrderData: [],
      // 全部评价数据
      allEvaluateData: [],
      // 技师项目信息
      serverInfo: {},
    };
  },
  watch: {},

  computed: {
    ...mapState("address", ["currentAddress"]),
    // 项目信息提取
    // projectInfo() {
    //   return {
    //     log: this.detailData.detail_log?.[0].url,
    //     nickname: this.detailData.nickname,
    //     score: this.detailData.score,
    //     status: this.detailData.server_status,
    //     point: this.detailData?.tableField116?.map((item) => item.project_name),
    //     qualification: this.detailData.qualifications,
    //     text: this.detailData.server_text,
    //     album: this.detailData?.server_album?.map((item) =>
    //       this.$photo(item.url)
    //     ),
    //   };
    // },
    // 整理订单数筛选
    filterOrderData() {
      return this.handleFilterData(this.allOrderData, "technician_id");
    },
    // 整理评价数筛选
    filterEvaluateData() {
      return this.handleFilterData(this.allEvaluateData, "server_id");
    },
    // 得到默认地址经纬度
    location() {
      let arr = this.currentAddress?.location?.split(",");
      return {
        lat: arr?.[1] || 0,
        lng: arr?.[0] || 0,
      };
    },
    // 获取技师项目信息
    inCludesProjectList() {
      return this.handleCurrentData(this.serverInfo?.includes_project);
    },
  },
  async onShow() {
    await this.$store.dispatch("address/getCurrentLocationData", {
      creatorUserId: this.$storage.get("UserInfo").id,
    });
    await this.getAllOrder();
    await this.getAllEvaluate();
  },
  async onReady() {
    // console.log("函数调用");
  },
  async onLoad({ serveId, infoId }) {
    await this.getDetailData(infoId);
    getModelInfo("65fbe6475efd5153ff566a8b", serveId).then(({ code, data }) => {
      if (code === 200) this.serverInfo = data;
    });
  },
  methods: {
    // 获取全部订单数
    async getAllOrder() {
      const { data } = await getModelList("65d571305efd5153ff562452", {
        currentPage: 1,
        pageSize: -1,
        filter: getSearchFilter({ is_cancel: 0 }, { method: "eq" }),
      });
      this.allOrderData = data?.list;
    },
    // 获取全部评价
    async getAllEvaluate() {
      const { data } = await getModelList("65b856b55efd5153ff55cd80", {
        currentPage: 1,
        pageSize: -1,
      });
      this.allEvaluateData = data?.list;
    },
    //获取当前位置
    getLocation() {
      let location = {
        lat: 0,
        lng: 0,
      };
      return new Promise((reserve, reject) => {
        //因为获取位置是异步接口所以需要使用promise
        uni.getLocation({
          success(res) {
            location.lat = res.latitude;
            (location.lng = res.longitude), reserve(location);
            // console.log(res.latitude, res.longitude);
          },
          fail(err) {
            reject(location); //获取失败则返回经纬坐标为0
          },
        });
      });
    },
    //根据金纬度计算距离
    distance(lat1, lng1) {
      var that = this;
      let lat2 = that.location.lat;
      let lng2 = that.location.lng;
      let rad1 = (lat1 * Math.PI) / 180.0;
      let rad2 = (lat2 * Math.PI) / 180.0;
      let a = rad1 - rad2;
      let b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
      let s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10000;
      s = s.toString();
      s = s.substring(0, s.indexOf(".") + 2);
      return s;
    },
    // 处理图片数组
    handleImg(arr) {
      return arr.map((item) => {
        return this.$photo(item.url);
      });
    },
    // 数据处理函数
    handleFilterData(arr, key = "_id") {
      return arr.reduce((obj, item) => {
        if (!obj[item[key]]) {
          obj[item[key]] = [];
        }
        obj[item[key]].push(item);
        return obj;
      }, {});
    },
    // 获取成绩平均值
    getAverageScore(id, key = "score") {
      let result = (
        this.filterEvaluateData[id]?.reduce(
          (total, item) => total + item[key],
          0
        ) / this.filterEvaluateData[id]?.length
      ).toFixed(2);

      return isNaN(result) ? 0 : Number(result);
    },
    // 整理获取弹出层数据
    handleCurrentData(arr) {
      return arr?.map((item) => {
        let [id, name] = item.split("/");
        return {
          id,
          name,
        };
      });
    },
    // 获取详情信息
    getDetailData(infoId) {
      getModelInfo("65c08a445efd5153ff55d908", infoId).then(
        ({ code, data }) => {
          if (code === 200) {
            this.detailData = data;
            // this.$nextTick(async () => {
            //   console.log("执行");
            //   const res = await this.$u.getRect(".introduction-album");
            //   console.log(res);
            // });
          }
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
%box-content {
  box-shadow: 0rpx 6rpx 18rpx 1rpx rgba(209, 209, 209, 0.4);
  border-radius: 15rpx;
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.user-detail {
  > image {
    width: 100%;
    height: 376rpx;
  }

  &-content {
    box-sizing: border-box;
    padding: 0 20rpx;

    .content-message {
      @extend %box-content;

      > view {
        padding: 10rpx;
        box-sizing: border-box;
      }

      .user-name {
        font-size: 32rpx;
        font-weight: 800;
      }

      .reservation {
        height: 50rpx;
        background: #c94117;
        border-radius: 25rpx;
        line-height: 50rpx;
        text-align: center;
        color: #333333;
        font-size: 26rpx;
        color: #ffffff;
        padding: 0 20rpx;
      }

      .star-number {
        color: #ffcd2a;
      }

      .order-number {
        font-size: 26rpx;
        color: #999999;

        text {
          padding-right: 16rpx;
        }
      }
    }

    .content-project {
      @extend %box-content;

      > view {
        font-size: 26rpx;
        color: #999;
        padding: 20rpx;
        box-sizing: border-box;
      }
    }

    .content-introduction {
      @extend %box-content;

      > view {
        padding: 20rpx;
        box-sizing: border-box;
      }

      .title {
        font-size: 32rpx;
        font-weight: 800;
        color: #333333;
      }

      .introduction-album {
        padding: 0 20rpx;
      }

      .introduction-text {
        font-size: 26rpx;
        color: #333333;
      }
    }
  }
}
</style>
